import requests, json
from os.path import isdir
from os import listdir


def postGps(url, gdata):
    # data = {'deviceid': str(deviceid), 'appkey': 'test', 'secret': 'test123', 'isstart': isstart, 'speed': speed,
    #         'heightOffset': height_offset, 'gngga': gpsdata}
    data = json.dumps(gdata)

    try:
        r = requests.post(url, {"param": data}, timeout=5)
        print("out of time!")
        return r
        # print("gps message:", r)
    except:
        print('post gps error')
        pass


def postFrame(url, data):
    imageDir = data['imgSaveDir']
    files = []
    if isdir(imageDir):
        for imgpath in listdir(imageDir):
            files.append(("inputStreams", (imgpath, open(f"{imageDir}/{imgpath}", "rb"), "image/jpg")))

    fdata = {
        'ctime': data["ctime"],
        'deviceid': str(data["deviceid"]),
        'heightOffset': str(data['height_offset']),
        'appkey': 'test',
        'secret': 'test123',
        'gngga': data['gpsdata'],
        'gpvtg': data['gpvtg'],
        'speed': data['speed'],
        'dcway': str(data['dcway']),
        'result': data['detections']
    }

    try:
        r = requests.post(url, data=fdata, files=files)
        return r
    except requests.exceptions.ConnectionError:
        print('Failed to establish a new connection: [Errno 111] Connection refused')
        return 'Connection refused'
    except:
        print("post frame error")
        pass


if __name__ == '__main__':
    from utils.tools import get_gps_data

    gps_url = 'http://123.57.233.58:8010/iot/secret/savePlaceList'
    picApi_url = 'http://123.57.233.58:8010/iot/secret/uploadPics'
    # gpsdata = '$GNGGA,073756.00,3040.8044103,N,12100.5956780,E,4,12,0.65,6.189,M,9.030,M,1.0,0926*56'

    result = [('crack', '69.34', (113, 369, 342, 440)), ('crack', '89.13', (184, 53, 274, 760))]

    for i in range(10):
        gpsdata = get_gps_data()
        # print('======', gpsdata)
        postGps(gps_url, 3321, gpsdata)
